import React, { Component } from 'react'
import {Button} from "antd";
import XLSX from "xlsx"
import common from "../../common";
/*props:{
	method:请求类型
	api:请求地址
	query:请求参数条件
	dataList:导出的数据(写了这个上三个可以不要写)
	columns:表头
	name:文件名(最好与功能模块挂钩)
}*/
var method;
var api;
var columns;
var name;
function Importfile(props) {
    debugger
    method= props.method
    name= props.name
    api= props.api
    columns= props.columns
    return(
        <div>
            <input type="file" name="picpath" id={name} style={{display:"none"}} onChange={importf} />
            <Button type="button"
                    onClick={f}>
                导入
            </Button>
        </div>
    )

}
var f=()=>{
    document.getElementById(name).click()
}
var wb;//读取完成的数据
var rABS = true; //是否将文件读取为二进制字符串
var importf=(obj)=>{//导入
    var f = document.querySelector('#'+name).files[0];
    var reader = new FileReader();
    reader.onload = function (e) {
        var data = e.target.result;
        if (rABS) {
            wb = XLSX.read(data, {
                type: 'binary'
            });
        } else {
            wb = XLSX.read(btoa(fixdata(data)), {//手动转化
                type: 'base64'
            });
        }
        //wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
        //wb.Sheets[Sheet名]获取第一个Sheet的数据
        var zuanyi=TurnEnglish(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]))
        common.ajax(method, api,{data:JSON.stringify(zuanyi)}).then(data => {
            common.toast("操作成功")
        })
    };
    if (rABS) {
        reader.readAsBinaryString(f);
    } else {
        reader.readAsArrayBuffer(f);
    }
}
function fixdata(data) { //文件流转BinaryString
    var o = "",
        l = 0,
        w = 10240;
    for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
    o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
    return o;
}
function TurnEnglish(a){
    const invertKeyValues = obj =>
        Object.keys(obj).reduce((acc, key) => {
            acc[obj[key]] = key;
            return acc;
        }, {});
    var kp={}
    columns.map((g)=>{
        if(!(g.dataIndex==undefined || g.dataIndex==null)){
            kp[g.dataIndex]=g.title;
        }
    })
    kp=invertKeyValues(kp)
    var ll=[]
    for(var i=0;i<a.length;i++){
        var c={}
        for(let key  in a[i]){
            if(kp[key]!=undefined){
                c[kp[key]]=a[i][key];
            }
        }
        ll.push(c)
    }
    return ll;
}
export default Importfile
